<?php

namespace app\api\controller;

use app\api\logic\AuthLogic;
use app\common\basic\BaseController;
use app\common\exception\ApiException;
use support\Request;
use support\Response;
use Webman\Push\Api;

class AuthController extends BaseController
{
    protected $logic;
    protected $validate;

    public function __construct()
    {
        $this->logic = new AuthLogic();
        parent::__construct();
    }

    /**
     * 用户登录
     * @param Request $request
     * @return Response
     */
    public function login(Request $request): Response
    {
        $username = $request->post('username');
        $password = $request->post('password');

        if (!$username || !$password) {
            return $this->fail('用户名和密码不能为空');
        }

        try {
            $result = $this->logic->login($username, $password);
            return $this->success($result, '登录成功');
        } catch (ApiException $e) {
            return $this->fail($e->getMessage());
        } catch (\Exception $e) {
            return $this->fail('登录失败');
        }
    }

    /**
     * 刷新访问令牌
     * @param Request $request
     * @return Response
     */
    public function refresh(Request $request): Response
    {
        $refreshToken = $request->post('refresh_token');

        if (!$refreshToken) {
            return $this->fail('刷新令牌不能为空');
        }
        try {
            $result = $this->logic->refreshToken($refreshToken);
            return $this->success($result, '刷新成功');
        } catch (ApiException $e) {
            throw new ApiException($e->getMessage(), $e->getCode());
        } catch (\Exception $e) {
            throw new ApiException('刷新失败', 402);
        }
    }

    /**
     * 用户退出
     * @param Request $request
     * @return Response
     */
    public function logout(Request $request): Response
    {
        $userId = $request->user['id'] ?? 0;
        
        if ($this->logic->logout($userId)) {
            return json(['code' => 200, 'msg' => '退出成功']);
        }
        
        return json(['code' => 500, 'msg' => '退出失败']);
    }
}